package jgl.vajra.driver.widget;


import android.graphics.Bitmap;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.ImageViewState;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.gyf.immersionbar.ImmersionBar;
import jgl.android.loadinglibrary.LoadingIndicatorView;
import jgl.vajra.driver.R;
import jgl.vajra.driver.databinding.ActivityBigImagePagerBinding;
import jgl.vajra.driver.databinding.ItemPagerImageBinding;
import jgl.vajra.driver.widget.base.BaseViewPagerAdapter;

import jgl.vajra.driver.widget.utils.BitmapUtils;
import jgl.vajra.driver.widget.utils.DisplayUtils;
import jgl.vajra.driver.widget.utils.FileUtils;
import jgl.vajra.driver.widget.utils.MD5Utils;
import jgl.vajra.driver.widget.utils.ToastUtils;
import jgl.vajra.driver.widget.databindingadapter.BaseBindingItemPresenter;
import jgl.vajra.driver.widget.databindingadapter.BaseDataBindingDecorator;
import jgl.vajra.driver.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.driver.widget.mvvm.view.BaseMVVMView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * 查看大图 glide
 */
public class BigImagePagerActivity extends BaseMVVMActivity implements BaseMVVMView, BaseViewPagerAdapter.BaseViewPageItemDecorator<String, ItemPagerImageBinding>, BaseViewPagerAdapter.BaseViewPageItemPresenter<String>, BaseDataBindingDecorator<String, ItemPagerImageBinding>, BaseBindingItemPresenter {
    public static final String INTENT_IMG_URLS = "imgUrls";
    public static final String INTENT_POSITION = "position";
    public static final String INTENT_IAG_TYPE = "imageType";
    ActivityBigImagePagerBinding binding;
    private List<View> pointViewList;
    private int imageType;
    public static final int TYPE_NET_IMAGE = 1;
    public static final int TYPE_FILE_IMAGE = 2;

    @Override
    public int getLayoutId() {
        return R.layout.activity_big_image_pager;
    }

    @Override
    protected int getStateBarColor() {
        return R.color.transparent;
    }

    @Override
    public void initView() {
        binding = (ActivityBigImagePagerBinding) mBinding;
        ImmersionBar.with(this).statusBarColor(R.color.transparent).init();
        // ToolbarUtils.initToolBar(binding.toolsBar,this);
        //  SystemBarTintManagerHelper.getInsatance().titleBarPaddingTop(binding.llTop );
        List<String> imgUrls = (List<String>) getIntent().getSerializableExtra(INTENT_IMG_URLS);
        int startPosition = getIntent().getIntExtra(INTENT_POSITION, 0);
        imageType = getIntent().getIntExtra(INTENT_IAG_TYPE, 1);
        binding.setView(this);
      /*  itemBinding.image.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CUSTOM);
        itemBinding.image.setMinScale(0.1F);*/
        //itemBinding.image.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CUSTOM);
        //  itemBinding.image.setMaxScale(10.0F);//最大显示比例（太大了图片显示会失真，因为一般微博长图的宽度不会太宽）

        pointViewList = new ArrayList<>();
        addGuidePointView(startPosition, imgUrls);
        BaseViewPagerAdapter adapter = new BaseViewPagerAdapter(imgUrls) {
            @Override
            public View getRootView() {
                return View.inflate(BigImagePagerActivity.this, R.layout.item_pager_image, null);
            }
        };
        adapter.setItemPresenter(this); adapter.setItemDecorator(this);
        binding.pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (View view : pointViewList) {
                    view.setSelected(false);
                }
                pointViewList.get(position).setSelected(true);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        binding.pager.setCurrentItem(startPosition);
        binding.pager.setOffscreenPageLimit(2);
        binding.pager.setAdapter(adapter);
      /*  smoothLinearLayoutManager = new SmoothLinea
      rLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        binding.recyclerView.setLayoutManager(smoothLinearLayoutManager);
        binding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int position = smoothLinearLayoutManager.findFirstVisibleItemPosition();
                    //得到指示器红点的位置
                    for (View view : pointViewList) {
                        view.setSelected(false);
                    }
                    pointViewList.get(position).setSelected(true);
                }
            }
        });
        PagerSnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(binding.recyclerView);
        binding.recyclerView.setAdapter(adapter);

        adapter.setItemDecorator(this);
        adapter.setItemPresenter(this);*/

    }

    private void addGuidePointView(int startPosition, List<String> imgUrls) {
        if (imgUrls != null && imgUrls.size() > 0) {
            pointViewList.clear();
            for (int i = 0; i < imgUrls.size(); i++) {
                if (!TextUtils.isEmpty(imgUrls.get(i))) {
                    View view = new View(this);
                    view.setBackgroundResource(R.drawable.selector_guide_bg);
                    view.setSelected(i == startPosition);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(DisplayUtils.dip2px(8),
                            DisplayUtils.dip2px(8));
                    layoutParams.setMargins(20, 0, 0, 0);
                    binding.guideGroup.addView(view, layoutParams);
                    pointViewList.add(view);
                }
            }
        }

    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {

    }


    @Override
    protected boolean isNeedLoadStatusBar() {
        return false;
    }

    @Override
    public boolean isUseProxy() {
        return false;
    }

    /*   @Override
       public void decorator(ItemPagerImageBinding binding, int position, int viewType, String data) {

       }*/
    @Override
    public void decorator(ItemPagerImageBinding itemBinding, int position, int viewType, String data) {

        if (imageType == TYPE_NET_IMAGE) {
            showNetImage(data, itemBinding.image, itemBinding.loading, itemBinding.save);

        } else {
            lookFileImage(data, itemBinding.image, itemBinding.loading, itemBinding.save);
        }

    }


    private void lookFileImage(final String imgurl, final SubsamplingScaleImageView imageView, final View loading, final TextView save) {

        File file = new File(imgurl);
        float initImageScale = BitmapUtils.getInitImageScale(file.getAbsolutePath(), BigImagePagerActivity.this);
        imageView.setMaxScale(initImageScale + 2.0f);//最大显示比例
        imageView.setImage(ImageSource.uri(Uri.fromFile(file)), new ImageViewState(initImageScale, new PointF(0, 0), 0));
/*
        Glide.with(getApplicationContext()).load(file)//
                .apply(new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                        .fitCenter()
                        .dontAnimate())
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        loading.setVisibility(View.GONE);
                        return false;
                    }
                })
                .into(imageView);
*/


        // notifyImage(file, save);
        //   ImageUitls.savePicRefreshGallery(BigImagePagerActivity.this, file);


    }

    private void showNetImage(final String imgUrl, final SubsamplingScaleImageView imageView, final LoadingIndicatorView loading, final TextView save) {
        Glide.with(BigImagePagerActivity.this).asBitmap().load(imgUrl).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                loading.smoothToHide();
                if (resource == null) return;

                float initImageScale = BitmapUtils.getInitImageScale(resource, BigImagePagerActivity.this);

                imageView.setMaxScale(initImageScale + 2.0f);//最大显示比例

                imageView.setImage(ImageSource.bitmap(resource), new ImageViewState(initImageScale, new PointF(0, 0), 0));
                imageView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                super.onLoadFailed(errorDrawable);
                loading.smoothToHide();
                if (imageView != null)
                    imageView.setImage(ImageSource.resource(R.drawable.ic_big_image_error));
            }
        });


    }

    private void notifyImage(final File bitmap, final String url, final TextView save) {
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FileUtils.saveFile(bitmap, MD5Utils.encode(url) + ".jpg", BigImagePagerActivity.this);
                save.setVisibility(View.GONE);
            }
        });
    }

    private void notifyImage(final File file, final TextView save) {
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save.setVisibility(View.GONE);
                ToastUtils.showShort("图片处于" + file.getAbsolutePath());

            }
        });
    }

    public void exitImageActivity() {
        BigImagePagerActivity.this.finish();
        BigImagePagerActivity.this.overridePendingTransition(R.anim.act_fade_in_center,
                R.anim.act_fade_out_center);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            exitImageActivity();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onViewPageItemClick(int position, String itemData) {

    }


    @Override
    public void onItemClick(int position, Object itemData) {

    }
}
